package com.jame.basics.thread.read_write;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * @author : Jame
 * @date : 2021-01-13 14:41
 **/
public class ReadWriteLockTest {
    public static void main(String[] args) {
        CaChe caChe = new CaChe();
        for (int i = 0; i < 5; i++) {
            final String temp = String.valueOf(i);
            new Thread(() -> {
                caChe.set(temp, temp);
            }).start();
        }
        for (int i = 0; i < 5; i++) {
            final String temp = String.valueOf(i);
            new Thread(() -> {
                String s = caChe.get(temp);
            }).start();
        }

    }
}

class CaChe {

    private Map<String, String> map = new HashMap<String, String>();

    private ReadWriteLock readWriteLock = new ReentrantReadWriteLock();

    public String get(String key) {
        readWriteLock.readLock().lock();
        try {
            System.out.println(Thread.currentThread().getName() + "开始读取");
            String s = map.get(key);
            System.out.println(Thread.currentThread().getName() + "读取完成");
            return s;
        } finally {
            readWriteLock.readLock().unlock();
        }
    }

    public void set(String key, String value) {
        readWriteLock.writeLock().lock();
        try {
        System.out.println(Thread.currentThread().getName() + "开始写入");
        map.put(key, value);
        System.out.println(Thread.currentThread().getName() + "写入完成");
        } finally {
            readWriteLock.writeLock().unlock();
        }
    }
}

